﻿using Bk.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data.Entity;

namespace WebApplication1.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        private bloggerEntitiesW db = new bloggerEntitiesW();

        public ActionResult Index()
        {
            var blogInfos = db.BlogInfo.Include(b => b.UserInfo).ToList();
            
            // 设置分类名称
            var categoryDict = new Dictionary<string, string>
            {
                { "1", "艺术" },
                { "2", "文学" },
                { "3", "体育" },
                { "4", "生活" }
            };
            
            foreach (var blog in blogInfos)
            {
                if (!string.IsNullOrEmpty(blog.categories + "") && categoryDict.ContainsKey(blog.categories + ""))
                    blog.categoriesName = categoryDict[blog.categories + ""];
            }
            
            return View(blogInfos);
        }

        // AJAX方法：根据分类获取博客文章
        public ActionResult GetPostsByCategory(int categoryId)
        {
            try
            {
                using (var context = new bloggerEntitiesW())
                {
                    IQueryable<BlogInfo> query = context.BlogInfo.Include(b => b.UserInfo);
                    
                    // 如果categoryId为0，显示所有文章；否则按分类筛选
                    if (categoryId > 0)
                    {
                        query = query.Where(b => b.categories == categoryId);
                    }

                    var blogInfos = query.ToList();
                    
                    // 设置分类名称
                    var categoryDict = new Dictionary<string, string>
                    {
                        { "1", "艺术" },
                        { "2", "文学" },
                        { "3", "体育" },
                        { "4", "生活" }
                    };
                    
                    foreach (var blog in blogInfos)
                    {
                        if (!string.IsNullOrEmpty(blog.categories + "") && categoryDict.ContainsKey(blog.categories + ""))
                            blog.categoriesName = categoryDict[blog.categories + ""];
                    }

                    // 返回部分视图
                    return PartialView("_BlogPostsPartial", blogInfos);
                }
            }
            catch (Exception ex)
            {
                return Content("<p style='color: red;'>加载内容时发生错误：" + ex.Message + "</p>");
            }
        }

        // AJAX方法：搜索博客文章
        public ActionResult SearchPosts(string searchTerm)
        {
            try
            {
                using (var context = new bloggerEntitiesW())
                {
                    var blogInfos = context.BlogInfo.Include(b => b.UserInfo).ToList();
                    
                    // 如果搜索词不为空，则进行搜索
                    if (!string.IsNullOrEmpty(searchTerm))
                    {
                        blogInfos = blogInfos.Where(b => 
                            b.title.Contains(searchTerm) || 
                            b.Substance.Contains(searchTerm) ||
                            (b.UserInfo != null && b.UserInfo.UserName.Contains(searchTerm))
                        ).ToList();
                    }
                    else
                    {
                        // 如果搜索词为空，返回空列表
                        blogInfos = new List<BlogInfo>();
                    }

                    // 返回部分视图
                    return PartialView("_BlogPostsPartial", blogInfos);
                }
            }
            catch (Exception ex)
            {
                return Content("<p style='color: red;'>搜索时发生错误：" + ex.Message + "</p>");
            }
        }

        [HttpPost]
        public ActionResult Index(string searchTerm)
        {
            var blogInfos = string.IsNullOrEmpty(searchTerm) ? new List<BlogInfo>() :
                db.BlogInfo.Where(b => b.Substance.Contains(searchTerm)).ToList();
            return View(blogInfos);
        }
        public ActionResult Art()
        {
            return View();

        }
        public ActionResult Wx()
        {
            return View();

        }
        public ActionResult Sports()
        {
            return View();

        }
        public ActionResult Life()
        {
            return View();

        }
        // 在你的控制器中确保有这些方法
        public ActionResult Increment(int id)
        {
            try
            {
                var post = db.BlogInfo.FirstOrDefault(b => b.BId == id); // 明确使用Id查询
                if (post == null)
                {
                    return Json(new { success = false, message = "博客不存在" });
                }
                post.Likes = post.Likes + 1; // 显式更新，避免歧义
                db.SaveChanges();
                return Json(new { success = true, count = post.Likes });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "操作失败：" + ex.Message });
            }
        }


        public ActionResult Decrement(int id)
        {
            var post = db.BlogInfo.Find(id);
            if (post == null || post.Likes <= 0) // 添加空值和负数判断
            {
                return Json(new { success = false, message = "操作失败" });
            }
            post.Likes--;
            db.SaveChanges();
            return Json(new { success = true, count = post.Likes });
        }

        //登录
        public ActionResult Login()
        {
            using (bloggerEntitiesW db = new bloggerEntitiesW())
            {
                var log = db.UserInfo.FirstOrDefault();
                return View();
            }
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(string UserName, string PassWord)
        {
            using (bloggerEntitiesW db = new bloggerEntitiesW())
            {
                var user = db.UserInfo.FirstOrDefault(u => u.UserName == UserName && u.PassWord == PassWord);
                if (user != null)
                {
                    Session["UserInfo"] = user.UserId;
                    if (user != null && user.UserName != null && user.UserId > 0)
                    {
                        //传ID到视图
                        return RedirectToAction("Index", "Default", new { id = user.UserId });
                    }
                    else
                    {
                        //传ID到个人视图
                        return RedirectToAction("Person", "Home", new { id = user.UserId });
                    }
                }
                else
                {
                    ViewBag.Error = "用户名或密码错误，请重试。";
                    return View();
                }
            }
        }
        public ActionResult Register()//注册页面，覃娟娟弄的
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]//2.

        public ActionResult Register(UserInfo users)
        {
            if (ModelState.IsValid)
            {
                using (bloggerEntitiesW db = new bloggerEntitiesW())
                {
                    try
                    {
                        // 检查用户名是否已存在
                        if (db.UserInfo.Any(u => u.UserName == users.UserName))
                        {
                            ModelState.AddModelError("UserName", "用户名已存在");
                            return View(users);
                        }
                        
                        // 检查手机号是否已存在
                        if (db.UserInfo.Any(u => u.Phone == users.Phone))
                        {
                            ModelState.AddModelError("Phone", "手机号已存在");
                            return View(users);
                        }

                        // 创建新的用户对象，只保存必要的字段
                        var newUser = new UserInfo
                        {
                            UserName = users.UserName,
                            PassWord = users.PassWord,
                            Phone = users.Phone,
                            Email = users.Email ?? "", // 如果为空则设为空字符串
                            State = 1, // 设置默认状态为1（激活状态）
                            Accounts = GenerateRandomAccount(), // 生成随机账户号
                            Image = "" // 设置默认头像为空
                        };

                        db.UserInfo.Add(newUser);
                        
                        if (db.SaveChanges() > 0)
                        {
                            return RedirectToAction("Login", "Default");
                        }
                        else
                        {
                            ModelState.AddModelError("", "注册失败，请重试");
                        }
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                    {
                        // 捕获验证异常并显示具体错误
                        foreach (var validationError in ex.EntityValidationErrors)
                        {
                            foreach (var error in validationError.ValidationErrors)
                            {
                                ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("", "注册时发生错误：" + ex.Message);
                    }
                }
            }
            return View(users);
        }

        // 生成随机账户号的方法
        private string GenerateRandomAccount()
        {
            Random rand = new Random();
            string account = "";
            for (int i = 0; i < 11; i++)
            {
                account += rand.Next(0, 9).ToString();
            }
            return account;
        }
    }
    
}
